<template>
  <div ref="stateSwitching" v-loading="isVisualVappShowLoadingProgress && isLoading" class="chartMain">
    <AdvancedLinkageToolbar :wid="widgetInstanceId" :config="config" />
    <div
      v-if="!isNoData && !isDataAbnormal"
      :id="`chartMain${chartId}`"
      ref="chartMainInner"
      class="chartMain-inner"
      style="width:100%;height: 100%;"
      :style="boxBgColor"
    >
      <Tooltip ref="Tooltip" :componentStyle="config.config.property.componentStyle" />
      <div class="state-switching-container">
        <div class="icon-container">
          <div v-if="Object.keys(stateInfo).length" class="img" :style="imgContainerStyle">
            <Icon v-if="haveIcon(stateInfo.icon)" v-visual-tooltip="getTooltip(stateInfo)" :conf="stateInfo.icon" @click="emitComponentMsg(stateInfo)" />
          </div>
        </div>
      </div>
    </div>
    <NoData
      :isNoData="isNoData && !isDataAbnormal"
      :boxBgColor="boxBgColor"
      :noDataTextColor="noDataTextColor"
      :noDataPromptType="config.config.property.noDataPromptType"
      :noDataPrompt="config.config.property.noDataPrompt"
    />
    <AbnormalData
      :isDataAbnormal="isDataAbnormal"
      :boxBgColor="boxBgColor"
      :noDataTextColor="noDataTextColor"
      :abnormalType="abnormalType"
    />
  </div>
</template>
<script>
import AdvancedLinkageToolbar from '@/components/common/advanced-linkage/advanced-linkage-toolbar.vue';
import Icon from '@/components/common/icon/icon.vue';
import chartBase from '@/mixin/chart-base.js';
import emitComponentBase from '@/mixin/emit-component-base.js';
import dataModel from '@/models/panel-config-data.js';
import { clone } from '@/utils/util.js';
import AbnormalData from '../common/abnormal-data/abnormal-data.vue';
import NoData from '../common/no-data/no-data.vue';
import Tooltip from '../common/tooltip/tooltip.vue';
import config from './config/config';
import { EMIT_PARAMS_OBJ } from '@/utils/constant';

export default {
  name: 'StaffLocationNew',
  components: {
    Icon,
    Tooltip,
    AbnormalData,
    NoData,
    AdvancedLinkageToolbar,
  },
  mixins: [chartBase, emitComponentBase],
  data() {
    const _config = clone(config.config.property);
    return {
      isLoading: false,
      isNoData: false,
      orgConfig: [],
      chartId: '',
      config: null,
      stateInfo: {},
      ..._config,
    };
  },
  computed: {
    imgContainerStyle() {
      const isAdaptive = this.config.config.property.isAdaptive === true;
      const adaptiveStyle = {
        width: '100%',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      };
      return isAdaptive ? adaptiveStyle : {};
    },
  },
  created() {
    this.orgConfig = config;
    this.config = clone(this.orgConfig);
    this.chartId = `${this.widgetInstanceId}_01`;
  },
  methods: {

    // 初始加载时 以及 编排面更改配置时 触发
    loadWidget(pageStatus) {
      this.pageStatus = pageStatus;
      this.updateConfigProperty();
      this.updateConfigData();

      if (window.isLocalEnv || this.emitComponentStatus) {
        this.updateParams(pageStatus);
        !this.isRealTime && this.debounceGetData();
      }
      this.afterLoadWidget();
      process.env.NODE_ENV === 'development' && this.mock();
    },

    mock() {
      clearInterval(this.timers.state);
      let timers = 0;
      this.timers.state = setInterval(() => {
        const status = timers % 2;
        const res = [{ status }];
        this.handleChartData(res);
        if (timers >= 40) {
          clearInterval(this.timers.state);
        }
        timers++;
      }, 1000);
    },

    // 接收xvue发来的图表数据
    handleChartData(result) {
      if (!result || !result.length) {
        return;
      }
      if (this.autoRefreshIsSameRes(result)) {
        result;
      }

      const { valueType } = this;
      const [{ status }] = clone(result);
      const [currentData = {}] = clone(result);
      const matchData =
        this.data.find(item => {
          if (valueType === 'string') {
            return String(item.status) === String(status);
          }
          return status >= item.min && status < item.max;
        }) || {};
      this.stateInfo = { ...matchData, ...currentData };
    },

    // 接收xvue发来的实时数据
    handleRealTimeCommunication(realTimeData) {
      this.isNoData = false;
      if (!realTimeData || !realTimeData.datalist || !realTimeData.datalist.length) {
        this.isNoData = true;
        return;
      }
      const [{ data }] = realTimeData.datalist;
      this.handleChartData(data);
    },
    getChartData() {
      const { data } = this.config.config;
      const { dataSourceType } = data;
      if (dataSourceType === 'staticData') {
        const result = this.getStaticData();
        this.isNoData = !result || !result.length;
        this.sendDataToConfig(result);
        this.handleChartData(result);

        // 重置数据异常状态
        this.resetAbnormalType();
        return;
      }
      this.autoRefresh();
      const method = `getChartData${dataSourceType}`;
      const params = this.getCorrectParams(this.params, dataSourceType);
      dataModel[method](params, data)
        .then(result => {
          // 重置数据异常状态
          this.resetAbnormalType();
          this.reportIfFieldsError(this.getParams()?.propertyMapping, result);
          this.isNoData = !result || !result.length;
          this.sendDataToConfig(result);
          this.handleChartData(result);
        })
        .catch(err => {
          this.handleChartDataError(err);
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    getTooltip(item) {
      const { cnName, dutyName, shiftTimeName } = item;
      return {
        config: this.tooltip || {},
        vars: { cnName, dutyName, shiftTimeName },
        params: this.params,
        parentComp: this,
      };
    },
    emitComponentMsg(params) {
      this.executeAction('', params);
      const configParameters = this.config.events[0].parameters;
      const parameters = {
        [configParameters[0].key]: params.status,
      };
      const keys = [configParameters[0].key];
      const evtKey = this.orgConfig.events[0].key;
      const outObj = {
        [EMIT_PARAMS_OBJ]: {
          eventKey: this.config.events[0].key,
          type: 'terms',
          isSharedParameter: this.isSharedParameter,
          widgetInstanceId: this.widgetInstanceId,
          keys,
          parameters,
          componentName: 'state_switching_component',
          sendTime: new Date().getTime(),
        },
      };
      this.emit(evtKey, outObj);

      // 发送联动面板的高级事件
      this.sendAdvancedLinkagge(params);
    },
  },
};
</script>
<style lang="less" scoped>
// 图表通用样式，主要有黑色loading 和 黑色 ‘没有数据’，样式名需一致
@import '../../common/chart.less';
// 蓝黑风格
.dark {
  background-color: #0d263a !important;
}
.state-switching-container {
  height: 100%;
  width: 100%;
  .icon-container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
